package com.wiscamp.ninechapters.panels.security;

import com.wiscamp.ninechapters.panels.application.services.RoleAppService;
import com.wiscamp.ninechapters.panels.application.services.UserAppService;
import com.wiscamp.ninechapters.panels.application.vo.RoleVO;
import com.wiscamp.ninechapters.panels.domain.repositories.UserRepository;
import cube.common.core.ParseUtils;
import cube.common.security.CurrentUser;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class CustomerUserDetailsService implements UserDetailsService {
    @Autowired
    private final UserRepository userRepository;

    @Autowired
    private final UserAppService userAppService;

    @Autowired
    private final RoleAppService roleAppService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        /*BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        var newPass  = encoder.encode("888888");*/

        var array = userName.split("::");
        if (array.length != 2) {
            throw new UsernameNotFoundException("User " + userName + " not found!");
        }

        var appId = ParseUtils.parseLong(array[0]);
        var userCode = array[1];
        var user = userRepository.getUserByCode(appId, userCode);

        if (user == null) {
            throw new UsernameNotFoundException("User " + userName + " not found!");
        }

        var roleIds = userAppService.getUserRoleIds(user.getUserId());
        var roles = roleAppService.getRolesByIds(roleIds);
        var roleCodes = roles.stream().map(RoleVO::getRoleCode).collect(Collectors.toList());
        roleCodes.add("ADMIN");
        var currentUser = new CurrentUser();
        currentUser.setApplicationId(appId);
        currentUser.setUserName(userName);
        currentUser.setUserCode(userCode);
        currentUser.setName(user.getUserName());
        currentUser.setTenantId(0);
        currentUser.setUserId(user.getUserId());
        currentUser.setPassword(user.getPassword());
        currentUser.setRoleCodes(roleCodes);

        return currentUser;
    }
}
